package cn.bx.bid.ctrl;


import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.User;
import cn.bx.bid.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
//@RequestMapping("/user")
//控制器
public class UserController {
    //添加日志
    private static final Logger Log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    //自动装载
    private UserService userService;

    @Value("${bid.savefilepath}")
    private String savefilepath;

    //请求地址
    //RequestParam  请求参数，基本类型或者数组都可以
    @RequestMapping(value = "userlogin", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map login(@RequestParam("userName") String u, @RequestParam("password") String p, HttpSession session) {
        User user = this.userService.login(u, p);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        session.setAttribute("User_Login", user);
        map.put("success", (user != null));
        Log.debug(user + "-----------");
        return map;
    }


    //checkUserNameRepeat检查用户名唯一
    //@RequestParam(value = "id",required = false) Long id      Long  包装类型可以为null   long   不能为null，0
    @RequestMapping(value = "checkUserNameRepeat")
    @ResponseBody
    public int checkUserNameRepeat(@RequestParam(value = "id", required = false) Long id, @RequestParam("userName") String userName) {
        //int i = this.userService.checkUserName(id, userName);
        return this.userService.checkUserName(id, userName);
    }

    @RequestMapping(value = "userGet", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public User userGet(@RequestParam("id") long id) {
        User user = this.userService.get(id);
        return user;
    }

    @RequestMapping(value = "userUpdate", produces = "application/json;charset=UTF-8")
    @ResponseBody
    //ModelAttribute  对象用这个注解
    public int userUpdate(@ModelAttribute("user") User user) {
        int isUpdate = this.userService.update(user);
        return isUpdate;
    }

    //@RequestMapping(value = "userSearch",produces = "application/json;charset=utf-8")
    @RequestMapping(value = "userSearch")
    @ResponseBody
    public Page<User> paging(@RequestParam(value = "page", defaultValue = "1") int pageNo, @RequestParam(value = "limit", defaultValue = "10") int limit, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "startDate", required = false) Date start, @RequestParam(value = "endDate", required = false) Date end) {
       /* ModelAndView mv=new ModelAndView();
        mv.addObject("name",name);
        mv.addObject("pageNo",pageNo);
        mv.addObject("limit",limit);
        mv.addObject("p",this.userService.paging(pageNo,limit,name,start,end));
        mv.setViewName("userlist");*/
        Page<User> page = this.userService.paging(pageNo, limit, name, start, end);
        return page;
    }


    //u还在上下文中，叫u
    //    @RequestMapping("userAdd")
    //    @ResponseBody
    //    public  int  userAdd(@ModelAttribute("u") User u){
    //        int r = this.userService.add(u);
    //        System.out.println(r);
    //        return r;
    //    }
    @RequestMapping(value = "userAdd", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object userAdd(@ModelAttribute("u") User u, @RequestParam("idcard2") MultipartFile f, HttpSession s) {
        if (f.isEmpty() == false) {
            String tname = f.getOriginalFilename();
            //  Log.info(">>>>>原始文件名："+tname+"表单域名"+f.getName());
            String suffix = tname.substring(tname.lastIndexOf('.'));
            String newFileName = UUID.randomUUID() + suffix;
            // String rootpath=s.getServletContext().getRealPath("images2");
            String rootpath = this.savefilepath;
            //   Log.info(">>>>>文件名位置："+rootpath+"/"+newFileName);
            //>>>u.setpictpath(newFileName);
            try {
                File temp = new File(rootpath);
                if (!temp.exists())
                    temp.mkdirs();
                f.transferTo(new java.io.File(temp, newFileName));
                u.setIdcard(newFileName);
            } catch (IOException e) {
                e.printStackTrace();
                Log.error("上传文件失败", e);
            }
        }
        int add = this.userService.add(u);
        return add;
    }

    //    @RequestMapping("userDel-{id}")
    //      PathVariable用在地址后面加参数  userDel-{id}
    //    public  String   userDel(@PathVariable("id") Long id, RedirectAttributes rd){
    //        int i = this.userService.userDel(id);
    //        rd.addFlashAttribute("userDelmsg",i>0?"删除成功":"删除失败");
    //        return "redirect:/userSearch.jhtml";
    //    }
    @RequestMapping("batchDelUser")
    @ResponseBody
    public Object batchDelUser(@RequestParam("ids[]") long[] ids) {
        int i = this.userService.batchDel(ids);
        return i;
    }


    @InitBinder
    public void init(WebDataBinder binder) {
        CustomDateEditor dateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true);
        binder.registerCustomEditor(Date.class, dateEditor);
    }
}
